package com.android.gestoraeropuertos;

import java.util.Date;
import java.util.GregorianCalendar;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.format.DateFormat;
import android.util.Log;

public class DbAdapter {

	public static final String KEY_CODE = "code";
	public static final String KEY_COUNTRY = "country";
	public static final String KEY_COUNTRYCODE = "country_code";
	public static final String KEY_DATE = "date";
	public static final String KEY_NOTE = "note";
	public static final String KEY_ROWID = "_id";

	private static final String TAG = "NotesDbAdapter";
	private DatabaseHelper mDbHelper;
	private SQLiteDatabase mDb;

	private static final String DATABASE_CREATE = "create table airports (_id integer primary key autoincrement, "
			+ "code text not null, country text not null, country_code text,  date number not null, note text null);";

	private static final String DATABASE_NAME = "data";
	private static final String DATABASE_TABLE = "airports";
	private static final int DATABASE_VERSION = 2;

	private final Context mCtx;

	private static class DatabaseHelper extends SQLiteOpenHelper {

		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(DATABASE_CREATE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
					+ newVersion + ", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS airports");
			onCreate(db);
		}
	}

	/**
	 * Constructor
	 * 
	 * @param ctx
	 *            the Context within which to work
	 */
	public DbAdapter(Context ctx) {
		this.mCtx = ctx;
	}

	/**
	 * Open the airports database. If it cannot be opened, try to create a new
	 * instance of the database. If it cannot be created, throw an exception to
	 * signal the failure
	 * 
	 * @return this (self reference, allowing this to be chained in an
	 *         initialization call)
	 * @throws SQLException
	 *             if the database could be neither opened or created
	 */
	public DbAdapter open() throws SQLException {
		mDbHelper = new DatabaseHelper(mCtx);
		mDb = mDbHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		mDbHelper.close();
	}

	/**
	 * Create a new airport using the code, country and date provided. If the
	 * line is successfully created return the new rowId for that line,
	 * otherwise return a -1 to indicate failure.
	 * 
	 * @param code
	 *            the code of the airport
	 * @param country
	 *            the country of the airport
	 * @param date
	 *            the date of airport visit
	 * @param note
	 *            the notes about the airport
	 * @return rowId or -1 if failed
	 */
	public long createAirport(String code, String country, String country_code,
			GregorianCalendar date, String note) {
		ContentValues initialValues = new ContentValues();
		initialValues.put(KEY_CODE, code);
		initialValues.put(KEY_COUNTRY, country);
		initialValues.put(KEY_COUNTRYCODE, country_code);
		initialValues.put(KEY_DATE, date.getTimeInMillis());
		initialValues.put(KEY_NOTE, note);

		return mDb.insert(DATABASE_TABLE, null, initialValues);
	}

	/**
	 * Delete the airport with the given rowId
	 * 
	 * @param rowId
	 *            id of airport line to delete
	 * @return true if deleted, false otherwise
	 */
	public boolean deleteAirport(long rowId) {
		return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
	}

	/**
	 * Return a Cursor over the list of all airports in the database
	 * 
	 * @return Cursor over all notes
	 */
	public Cursor fetchAllAirports() {

		return mDb.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_CODE,
				KEY_COUNTRY, KEY_COUNTRYCODE, KEY_DATE, KEY_NOTE }, null, null,
				null, null, KEY_DATE + " DESC");
	}

	/**
	 * Return a Cursor positioned at the airport that matches the given rowId
	 * 
	 * @param rowId
	 *            id of airport to retrieve
	 * @return Cursor positioned to matching airport, if found
	 * @throws SQLException
	 *             if note could not be found/retrieved
	 */
	public Cursor fetchAirport(long rowId) throws SQLException {

		Cursor c = mDb.query(true, DATABASE_TABLE, new String[] { KEY_ROWID,
				KEY_CODE, KEY_COUNTRY, KEY_COUNTRYCODE, KEY_DATE, KEY_NOTE },
				KEY_ROWID + "=" + rowId, null, null, null, null, null);
		if (c != null) {
			c.moveToFirst();
		}
		return c;
	}

	/**
	 * Update the airport using the details provided. The line to be updated is
	 * specified using the rowId, and it is altered to use the code, country,
	 * date and notes passed in
	 * 
	 * @param rowId
	 *            id of line to update
	 * @param code
	 *            value to set airport code to
	 * @param contry
	 *            value to set airport country to
	 * @param date
	 *            value to set airport visit date to
	 * @param note
	 *            value to set airport notes to
	 * @return true if the line was successfully updated, false otherwise
	 */
	public boolean updateAirport(long rowId, String code, String country, String country_code,
			GregorianCalendar date, String note) {
		ContentValues args = new ContentValues();
		args.put(KEY_CODE, code);
		args.put(KEY_COUNTRY, country);
		args.put(KEY_COUNTRYCODE, country_code);
		args.put(KEY_DATE, date.getTimeInMillis());
		args.put(KEY_NOTE, note);

		// DateFormat dateFormat = new DateFormat();
		// dateFormat.
		return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
	}
}
